#include "mythr_translation.h"
#include<qdebug.h>
#include<qfile.h>

mythr_translation::mythr_translation(QObject *parent) : QObject(parent)
{
    //
    connect(this,&mythr_translation::signal_cunrushujuku,this,&mythr_translation::slot_cunrushujuku);

    manager = new QNetworkAccessManager(NULL);
    connect(manager,SIGNAL(finished(QNetworkReply*)),this,SLOT(ReplyFinished(QNetworkReply*)));
    connect(&timer_helpover,&QTimer::timeout,[=](){timer_helpover.stop(); this->translation(*eng[biaoshi_chi]);});

}
//翻译

int mythr_translation::getmaxlinenum(QString filename)
{
       QFile txt(filename);
       QByteArray arr[4];
       if(txt.open(QIODevice::ReadOnly))
       {

           while(txt.atEnd()==false)
           {
               for(int i=0;i<4;i++)
               {
                    arr[i]=txt.readLine();

               }

           }
           txt.close();
       }

       QString temp;
       temp=arr[0];
       return temp.toInt();
}


void mythr_translation::sql_trans(int id,QString filename)//线程函数2
{
     qDebug()<<"mythr_translation";

    //获得最大行数
    maxline=this->getmaxlinenum(filename);
    qDebug()<<"获得最大行数="<<maxline;
    maxline=maxline+1;

    //英文
    this->eng=new QString*[maxline] ;//何时delete？用完时
    for(int i= 0;i<maxline;i++)
    {
        eng[i]=new QString;
    }

    //数据库:
    QSqlDatabase mysql;
    if(QSqlDatabase::contains("qt_sql_default_connection"))
      mysql = QSqlDatabase::database("qt_sql_default_connection");
    else
      mysql = QSqlDatabase::addDatabase("QSQLITE");
    mysql.setDatabaseName("../myshujuku_engchi.db");

    if(mysql.open()==true)
    {
        QSqlQuery query(mysql);//不可以做成员,会报错
        //
        query.exec("DROP TABLE english");
        //创建表
        query.exec("create table english(id int primary key, time double,eng varchar(600), trans_id int )");
        //字幕文件
        QFile txt(filename);
        if(txt.open(QIODevice::ReadOnly))
        {
            QByteArray arr[4];
            int j=0;
            while(txt.atEnd()==false)
            {
                for(int i=0;i<4;i++)
                    arr[i]=txt.readLine();
                //待翻译的文本
                *eng[j]=arr[2];
                j++;
                //时间转换
                double time=this->totime(arr[1]);
                //
                QString eng=arr[2];
                eng=eng.replace(QRegExp("'"),QString("''"));
                QSqlQuery query;//不可以做成员,会报错
                //插入数据
                //qDebug()<<arr[0].data()<<time<<eng;
                query.exec(QString("insert into english(id,time,eng,trans_id) values(%1,%2,'%3',%4)").arg(arr[0].data()).arg(time).arg(eng).arg(id) );
                //最大id
                QString tmep;
                tmep=arr[0];

            }

            txt.close();
        }
    mysql.close();
    }

    //中文
    this->biaoshi_chi=0;
    this->translation(*eng[biaoshi_chi]);


    return;
}



void mythr_translation::translation(QString str)
{
    Translator translator;
    translator.setappid();
    translator.SetQstr(str);     //传入需要翻译内容

    QString url = translator.GetUrl();     //获取url
    qDebug()<<url;
    //1. 创建一个请求
    QNetworkRequest request;
    request.setUrl(QUrl(url));
    //2. 创建一个管理器

    //3. 连接请求结束信号

    //4. 发送GET请求
    manager->get(request);

    return;

}



void mythr_translation::ReplyFinished(QNetworkReply *reply)
{

    QVariant status_code = reply->attribute
            (QNetworkRequest::HttpStatusCodeAttribute);
    if(reply->error() == QNetworkReply::NoError)
    {
        QByteArray bytes = reply->readAll();  //获取字节
        QString result(bytes);  //转化为字符串
        QJsonObject data(QJsonDocument::fromJson(bytes).object());
        QString string = data["trans_result"].toArray()[0].toObject()["dst"].toString();
        //
        *eng[this->biaoshi_chi]=string;
        qDebug()<<"mythr"<<biaoshi_chi<< string;

        biaoshi_chi++;//往后移
        if(biaoshi_chi==this->maxline)//for(int i=0;i<maxline;i++)
        {

            emit signal_cunrushujuku();

        }
        else{

            //一个一个来
            if(biaoshi_chi==300)//大于319会抛出异常
            {
               emit signal_trans_next(eng,biaoshi_chi,maxline);

               return;
            }

            timer_helpover.start(1000);//结束当次连接,this->translation(*eng[biaoshi_chi]);是递归,多次重复链接
//            this->translation(*eng[biaoshi_chi]);
              emit signal_showproject(QString("正在翻译中...\n"+string),(double)biaoshi_chi/(double)maxline);//qDebug()<<"trans"<<biaoshi_chi/maxline;
        }

    }
    delete reply;

    return;
}

void mythr_translation::slot_cunrushujuku()
{

     this->cunrushujuku();
     emit signal_fanyiover();
     return;
}



void mythr_translation::cunrushujuku()
{
    qDebug()<<"void mythr_translation::cunrushujuku()";
    //数据库:
    QSqlDatabase mysql;
    if(QSqlDatabase::contains("qt_sql_default_connection"))
      mysql = QSqlDatabase::database("qt_sql_default_connection");
    else
      mysql = QSqlDatabase::addDatabase("QSQLITE");
    mysql.setDatabaseName("../myshujuku_engchi.db");

    if(mysql.open()==true)
    {
        QSqlQuery query;
        //
        query.exec("DROP TABLE chinese");
        query.exec("create table chinese(id int primary key, time double,chi varchar(600))");

        for(int i=0;i<this->maxline;i++)
        {
            double time=0;
            QSqlQuery query;
            query.exec(QString("select * from english where id = %1").arg(i));
            if(query.first()==true)
            {
                time=query.value("time").toDouble();

            }
             //qDebug()<<"id="<<i<<"time="<<time<<"chi"<<*eng[i];
             query.exec(QString("insert into chinese(id,time,chi) values(%1,%2,'%3')").arg(i).arg(time).arg(*eng[i]) );
        }


        mysql.close();
    }


    //用完delete
    delete [] eng;
    //this->timer.start(6000);//QObject::startTimer: Timers cannot be started from another thread

    return;
}


double mythr_translation::totime(QByteArray arrtime)
{
    QString buf_time(arrtime);
    char* p=buf_time.toUtf8().data();
    double time=0;

    double time_3;
//3
    for(int i=0;i<=9;i++)
    {
        if(p[9]==QString("%1").arg(i))
            time_3=0.1*i;

    }
//2
    double time_2[2];
    for(int i=0;i<=9;i++)
    {
        if(p[6]==QString("%1").arg(i))
            time_2[0]=10*i;

    }
    for(int i=0;i<=9;i++)
    {
        if(p[7]==QString("%1").arg(i))
            time_2[1]=i;

    }
    //1
    double time_1[2];
    for(int i=0;i<=9;i++)
    {
        if(p[3]==QString("%1").arg(i))
            time_1[0]=10*i*60;

    }
    for(int i=0;i<=9;i++)
    {
        if(p[4]==QString("%1").arg(i))
            time_1[1]=i*60;

    }

    time=time_3+time_2[0]+time_2[1]+time_1[0]+time_1[1];

    delete []  p;
    return time;
}
